// pages/login/login.js
const utils = require('../../utils/index')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userImg:'',
    loginName:'',//缓存的登录用户名
    loginPassword:''//缓存登录密码
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this;
    wx.getStorage({
      key: 'loginName',
      success (res) {
        _this.setData({
          loginName:res.data
        })
      }
    })
    wx.getStorage({
      key: 'loginPassword',
      success (res) {
        _this.setData({
          loginPassword:res.data
        })
      }
    })
  },
  formSubmit(e){
    let loginName = e.detail.value.account;
    let loginPassword = e.detail.value.password;
    if(!!e.detail.value.account && !!e.detail.value.password){
      wx.request({
        url: app.globalData.baseServePath + '/wxapi/login',
        method:'POST',
        header:{
          'content-type': 'application/x-www-form-urlencoded'
        },
        data:{
          username:loginName,
          password:loginPassword,
          loginType:'1'
        },
        success(res){
          if(res.statusCode == 200){ 
            if(res.data.code == 200){
              let token = res.data.token;
              let user = res.data.user;
              utils.setStorage({
                'token':token,
                'userInfo':user,
                'loginName':loginName,
                'loginPassword':loginPassword
              }).then((res)=>{
                app.globalData.token = token;
                app.globalData.userInfo = user;                      
                wx.showToast({
                  title: '登录成功',
                  icon: 'success',
                  duration: 2000,
                  success(res){
                    setTimeout(()=>{
                      wx.navigateBack({
                        delta:1,
                        success: function (e) {
                          var page = getCurrentPages().pop();
                          if (page == undefined || page == null) return;
                              page.onLoad();
                            }
                      },);
                    },1000)
                  }
                })
              })             
            }else{
              wx.showModal({
                title: '错误',
                content: res.data.msg
              })
            }
            
          }
        }
      })
    }else{
      wx.showModal({
        title: '错误',
        content: '请填写用户名和密码'
      })
    }
    
  }
})